﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Microsoft.ApplicationBlocks.Data;
using Active.Modules.Social;
using System.Threading;
using System.Xml;
using DotNetNuke.Services.Journal.Internal;

namespace DotNetNuke.Modules.ActiveSocialMigrator.Data
{
    public class JournalDB : Connection
    {
        internal void MoveComments(int OldJournalId) {
            string sqlText = "SELECT TOP 1 JournalId FROM " + databaseOwner + objectQualifier + "Journal WHERE ObjectKey = 'AS{0}'";
            sqlText = String.Format(sqlText, OldJournalId);
            int JournalId = Convert.ToInt32(SqlHelper.ExecuteScalar(connectionString, CommandType.Text, sqlText));
            using (IDataReader dr = Comments_List(OldJournalId, -1)) 
            {
                while (dr.Read()) {
                    var ci = new DotNetNuke.Services.Journal.CommentInfo { JournalId = JournalId, Comment = HttpUtility.UrlDecode(dr["Comment"].ToString()) };
                    if (ci.Comment.Length > 2000) {
                        ci.Comment = ci.Comment.Substring(0, 1999);
                        
                    }
                    ci.UserId = Convert.ToInt32(dr["UserId"].ToString());

                    SqlHelper.ExecuteNonQuery(connectionString, databaseOwner + objectQualifier + "asmigrate_CommentsSave", JournalId, ci.UserId, ci.Comment, dr["DateCreated"]);
                }
                dr.Close();
            }
        }
        internal IDataReader Comments_List(int ItemId, int ItemType) {
            return SqlHelper.ExecuteReader(connectionString, databaseOwner + objectQualifier + "activesocial_Comments_List", ItemId, ItemType);
        }
        internal IDataReader Journal_Types(int PortalId) {
            return SqlHelper.ExecuteReader(connectionString, databaseOwner + objectQualifier + "activesocial_Journal_GetTypes", PortalId);
        }
        internal void UpdateJournalDates(int JournalId, DateTime DateCreated)
        {
            string sqlText = "UPDATE " + databaseOwner + objectQualifier + "Journal SET DateCreated = '{1}' WHERE ObjectKey = 'AS{2}'";
            sqlText = String.Format(sqlText, dbPrefix, DateCreated, JournalId);
            SqlHelper.ExecuteNonQuery(connectionString, CommandType.Text, sqlText);
        }
        internal IDataReader Journal_List(int PortalId, int CurrentUserId, int ProfileId, int GroupId, int JournalTypeId, int RowIndex, int MaxRows, string FilterTypes, int JournalMode, string JournalQuery)
        {
         
            return SqlHelper.ExecuteReader(connectionString, databaseOwner + objectQualifier + "asmigrate_Journal_ListForSummary", PortalId, CurrentUserId, ProfileId, GroupId, JournalTypeId, RowIndex, MaxRows);
           
        }
        public List<JournalInfo> JournalList(int PortalId, int UserId, int ProfileId, int GroupId, int JournalTypeId, int RowIndex, int MaxRows, string FilterTypes, int JournalMode, string JournalQuery)
        {
            List<JournalInfo> jl = new List<JournalInfo>();
            Data.JournalDB db = new Data.JournalDB();
            JournalInfo ji = null;
            IDataReader dr = null;
            System.Globalization.DateTimeFormatInfo dtFI = new System.Globalization.CultureInfo("en-US", false).DateTimeFormat;
            if ((Thread.CurrentThread.CurrentCulture != null))
            {
                dtFI = Thread.CurrentThread.CurrentCulture.DateTimeFormat;
            }

            try
            {
                
                dr = db.Journal_List(PortalId, UserId, ProfileId, GroupId, JournalTypeId, RowIndex, MaxRows, FilterTypes, JournalMode, JournalQuery);
                
                XmlDocument xDoc = default(XmlDocument);
                while (dr.Read())
                {
                    ji = new JournalInfo();
                    {
                        ji.ItemCount = int.Parse(dr["ItemCount"].ToString());
                        ji.JournalId = int.Parse(dr["JournalId"].ToString());
                        ji.JournalTypeId = int.Parse(dr["JournalTypeId"].ToString());
                        ji.JournalType = dr["JournalType"].ToString();
                        ji.Subject = dr["Subject"].ToString();
                        ji.UserId = int.Parse(dr["UserId"].ToString());
                        if (!string.IsNullOrEmpty(dr["DateCreated"].ToString()))
                        {
                            ji.DateCreatedGMT = System.DateTime.Parse(dr["DateCreated"].ToString());
                            string dtString = dr["DateCreated"].ToString();
                            ji.DateCreated = System.DateTime.Parse(dtString, dtFI);
                           

                        }
                        if (!string.IsNullOrEmpty(dr["DateUpdated"].ToString()))
                        {
                            string dtuString = dr["DateUpdated"].ToString();
                            ji.DateUpdated = System.DateTime.Parse(dtuString, dtFI);
                        }
                        ji.DisplayOption = int.Parse(dr["DisplayOption"].ToString());
                        ji.PortalId = int.Parse(dr["PortalId"].ToString());
                        ji.IsPrivate = bool.Parse(dr["IsPrivate"].ToString());
                        ji.Image = dr["Image"].ToString();
                        ji.JournalData = dr["JournalData"].ToString();
                        //.JournalSource = CType(CInt(dr["JournalSource"].ToString()), JournalSources)
                        ji.JournalOwnerId = int.Parse(dr["JournalOwnerId"].ToString());
                        ji.Icon = dr["Icon"].ToString();
                        ji.JournalAuthor = new JournalEntity(dr["JournalAuthor"].ToString());
                        ji.JournalOwner = new JournalEntity(dr["JournalOwner"].ToString());
                        ji.Group = new JournalEntity(dr["Group"].ToString());
                        ji.Profile = new JournalEntity(dr["Profile"].ToString());
                        ji.Summary = dr["Summary"].ToString();
                        if (ji.JournalTypeId == 8)
                        {
                            //Note
                            ji.Summary = Utilities.Text.InsertLineBreaks(ji.Summary, 3);
                        }

                        ji.Template = dr["Template"].ToString();
                        ji.GroupId = int.Parse(dr["GroupId"].ToString());
                        ji.ProfileUserId = int.Parse(dr["ProfileId"].ToString());
                        ji.Likes = new List<LikeItem>();
                        if (!string.IsNullOrEmpty(ji.JournalData))
                        {
                            try
                            {
                                ji.JournalDataItems = JournalDataItems.GetJournalData(ji.JournalData);

                            } catch (Exception ex)
                            {
                            }
                            try
                            {
                                xDoc = new XmlDocument();
                                xDoc.LoadXml(ji.JournalData);
                                XmlNodeList xLikes = xDoc.DocumentElement.SelectNodes("//likes/user");
                                if ((xLikes != null))
                                {
                                    foreach (XmlNode xLike in xLikes)
                                    {
                                        int uid = Convert.ToInt32(xLike.Attributes["userid"].Value);
                                        if (uid == UserId)
                                        {
                                            ji.ViewerLikes = true;
                                        }
                                        ji.Likes.Add(new LikeItem(uid, xLike.Attributes["name"].Value));
                                    }
                                }

                            } catch (Exception ex)
                            {
                            }
                        }
                        if (string.IsNullOrEmpty(dr["ShortSubject"].ToString()))
                        {
                            ji.ShortSubject = ji.Subject;
                        } else
                        {
                            ji.ShortSubject = dr["ShortSubject"].ToString();
                        }
                        //If Not String.IsNullOrEmpty(dr["ProfileTemplate"].ToString()) Then
                        //    .ProfileTemplate = dr["ProfileTemplate"].ToString()
                        //End If
                        //If Not String.IsNullOrEmpty(dr["GroupTemplate"].ToString()) Then
                        //    .GroupTemplate = dr["GroupTemplate"].ToString()
                        //End If
                        //If Not String.IsNullOrEmpty(dr["SiteTemplate"].ToString()) Then
                        //    .SiteTemplate = dr["SiteTemplate"].ToString()
                        //End If
                        ji.CanComment = bool.Parse(dr["CanComment"].ToString());
                        if (!string.IsNullOrEmpty(dr["SecuritySet"].ToString()) )
                        {
                            ji.Security = dr["SecuritySet"].ToString();
                        } else
                        {
                            ji.Security = string.Empty;
                        }

                    }


                    jl.Add(ji);
                }

                dr.Close();
                dr = null;
            } catch (Exception ex)
            {
                Exceptions.LogException(ex);
            } finally
            {
                if ((dr != null))
                {
                    if (!dr.IsClosed)
                    {
                        dr.Close();
                        dr = null;
                    }
                }


            }



            return jl;
        }
    }
}